






# Clean fewsnet values ----------------------------------------------------

shp_cleaner <- function(shp) {
  
  if("CS" %in% colnames(shp) == TRUE)
    shp %>% mutate(CS = ifelse(CS > 5, NA, CS),
                   CS = ifelse(CS == 0, NA, CS))
  
  else(
    if("ML1" %in% colnames(shp) == TRUE)
      shp %>% mutate(ML1 = ifelse(ML1 > 5, NA, ML1),
                     ML1 = ifelse(ML1 == 0, NA, ML1))
    else(  
      if("ML2" %in% colnames(shp) == TRUE)
        shp %>% mutate(ML2 = ifelse(ML2 > 5, NA, ML2),
                       ML2 = ifelse(ML2 == 0, NA, ML2))))
  
  
}







# Match units -------------------------------------------------------------

finder <- function(data, shp) {
  data %>% 
    map(~st_join(.x, shp, join = st_intersects))
}



load_adm1 <- function() {
  # All countries in Africa + Yemen
  afnames <- raster::ccodes() %>% 
    filter(continent == "Africa" | NAME == "Yemen") %>% 
    dplyr::select(NAME)
  temp1 <- vector("list", 0)
  for(i in afnames$NAME) {
    print(i)
    temp1[[i]] <- raster::getData(name = "GADM", 
                                  country = i, 
                                  download = T, 
                                  level = 1, path = here::here("Shapefiles"))
  }
  
  # Join into sf frame
  joined1 <- list(temp1, makeUniqueIDs = T) %>% 
    purrr::flatten() %>% 
    do.call(rbind, .) %>% 
    st_as_sf()
}


# Rasterize ---------------------------------------------------------------

to_raster <- function(x, extentOf, field, resolution, fun = "mean") {
  library(raster)
  library(fasterize)
  
  
  r <- raster(extent(extentOf),
              resolution = resolution,
              crs = st_crs(x)$proj4string)
  
  fasterize(x, r, field = field, fun = fun)
  
}


raster_to_sf <- function(x) {
  library(sp)
  
  as(x, "SpatialPolygonsDataFrame") %>% 
    st_as_sf()
  
}


dater <- function(x, type) {
  library(lubridate)
  if(type == "CS") {
    x %>% 
      mutate(year = as.numeric(substr(date_code, 1,4)),
             month = substr(date_code, 5,6),
             date_cs = lubridate::ymd(paste0(year, "-", month, "-", "01")))
  }
  else(
    if(type == "ML2") {
      x %>%
        mutate(year = as.numeric(substr(date_code, 1,4)),
               month = substr(date_code, 5,6),
               date_cs = lubridate::ymd(paste0(year, "-", month, "-", "01")),
               date_ml2 = if_else(date_cs < lubridate::ymd("2016-02-01"),
                                  date_cs %m+% months(3),
                                  date_cs %m+% months(4)))
    }
    
    else(
      if(type == "ML1") {
      x %>%
        mutate(year = as.numeric(substr(date_code, 1,4)),
               month = substr(date_code, 5,6),
               date_cs = lubridate::ymd(paste0(year, "-", month, "-", "01")),
               date_ml1 = if_else(date_cs < lubridate::ymd("2016-02-01"),
                                  date_cs %m+% months(1),
                                  date_cs %m+% months(1)))
    }
    )
  )
  
}
